using System;
using System.IO;

namespace Tsanie.ShellExtension.Util {

    public static class ByteExtension {
        public static uint ToUInt(this byte[] bs, int length) {
            if (bs == null || bs.Length < length)
                return 0;
            uint rtn = 0;
            for (int i = 0; i < length; i++) {
                rtn <<= 8;
                rtn |= bs[i];
            }
            return rtn;
        }
        public static double ToDouble(this byte[] bs) {
            if (bs == null || bs.Length < 8)
                return 0;
            byte[] b2 = new byte[8];
            for (int i = 0; i < 8; i++) {
                b2[i] = bs[7 - i];
            }
            return BitConverter.ToDouble(b2, 0);
        }
        public static short ReadUI16(this Stream src) {
            if (src == null)
                return 0;
            byte[] bs = new byte[2];
            if (src.Read(bs, 0, 2) < 2)
                return 0;
            return (short)((bs[0] << 8) | bs[1]);
        }
        public static uint ReadUI24(this Stream src) {
            if (src == null)
                return 0;
            byte[] bs = new byte[3];
            if (src.Read(bs, 0, 3) < 3)
                return 0;
            return bs.ToUInt(3);
        }
        public static uint ReadUI32(this Stream src) {
            if (src == null)
                return 0;
            byte[] bs = new byte[4];
            if (src.Read(bs, 0, 4) < 4)
                return 0;
            return bs.ToUInt(4);
        }
        public static string ToTimeString(this uint time) {
            return string.Format("{0}:{1:D2}.{2:D3}",
                time / 60000,
                time / 1000 % 60,
                time % 1000);
        }
    }

    public static class StringExtension {
        public static string ToPathWithoutExt(this string file) {
            if (file == null)
                return null;
            int i = file.LastIndexOf('.');
            if (i < 0)
                return file;
            return file.Substring(0, i);    // C:\123.txt
        }
    }

}